<template>
        <el-container class="container">
            <el-aside class="folder-aside">
                <div>
                    <el-input v-model="folderName" placeholder="请输入文件夹名称" clearable size="small" prefix-icon="el-icon-search" style="margin-bottom: 20px"/>
                </div>
                <div>
                    <el-tree :data="folderTree" :props="defaultProps" :expand-on-click-node="false" :filter-node-method="filterNode" :current-node-key="rootNodeId" node-key="id" ref="tree" default-expand-all highlight-current @node-click="nodeClick"/>
                </div>
            </el-aside>
            <div class="file-container" v-contextmenu:contextMenu @contextmenu.prevent.stop="rightClick('container')">
                <el-breadcrumb separator-class="el-icon-arrow-right" class="bread">
                    <el-breadcrumb-item v-for="bread in breadList"><a href="javascript:void(0)" @click="goInToFolder(bread.id)">{{bread.name}}</a></el-breadcrumb-item>
                </el-breadcrumb>
                <div :class="'file-list '+mode">
                    <div v-for="folder in folderList" class="item" @dblclick="goInToFolder(folder.id)" v-contextmenu:contextMenu @contextmenu.prevent.stop="rightClick('folder',folder.id,folder.name)">
                        <el-image class="img" :src="require('@/assets/images/am/filext/open-folder.png')" fit="fill"></el-image>
                        <div class="file-name">{{folder.name}}</div>
                    </div>
                    <div v-for="file in fileList" class="item" v-contextmenu:contextMenu @contextmenu.prevent.stop="rightClick('file',file.id,file.title)">
                        <el-image class="img" :src="formatImg(file.url)" fit="fill"></el-image>
                        <div class="file-name">{{file.title}}</div>
                    </div>
                </div>
            </div>


            <v-contextmenu ref="contextMenu">
                <!--     容器区域右键菜单   -->
                <v-contextmenu-submenu title="排序方式" v-show="rightClickFolderOrFile=='container'">
                    <v-contextmenu-item>按照名称排序</v-contextmenu-item>
                    <v-contextmenu-item>按照创建时间排序</v-contextmenu-item>
                    <v-contextmenu-item>按照修改时间排序</v-contextmenu-item>
                </v-contextmenu-submenu>
                <v-contextmenu-item @click="changeMode('bigImg')" v-show="rightClickFolderOrFile=='container'"><i class="el-icon-menu"></i><span>大图模式</span></v-contextmenu-item>
                <v-contextmenu-item @click="changeMode('col')" v-show="rightClickFolderOrFile=='container'"><i class="el-icon-s-unfold"></i><span>列表模式</span></v-contextmenu-item>
                <v-contextmenu-item @click="refreshFolder" v-show="rightClickFolderOrFile=='container'"><i class="el-icon-refresh"></i><span>刷新</span></v-contextmenu-item>
                <v-contextmenu-item @click="openAddFolder" v-show="rightClickFolderOrFile=='container'"><i class="el-icon-circle-plus-outline"></i><span>新建文件夹</span></v-contextmenu-item>
                <v-contextmenu-item @click="addFile" v-show="rightClickFolderOrFile=='container'"><i class="el-icon-plus"></i><span>上传档案</span></v-contextmenu-item>
                <!--     文件夹右键菜单   -->
                <v-contextmenu-item @click="viewDetailFolder" v-show="rightClickFolderOrFile=='folder'"><i class="el-icon-warning-outline"></i><span>查看信息</span></v-contextmenu-item>
                <v-contextmenu-item @click="renameFolder" v-show="rightClickFolderOrFile=='folder'"><i class="el-icon-edit-outline"></i><span>重命名</span></v-contextmenu-item>
                <v-contextmenu-item @click="authFolder" v-show="rightClickFolderOrFile=='folder'"><i class="el-icon-link"></i><span>授权</span></v-contextmenu-item>
                <v-contextmenu-item @click="moveFolder" v-show="rightClickFolderOrFile=='folder'"><i class="el-icon-thumb"></i><span>移动</span></v-contextmenu-item>
                <v-contextmenu-item @click="deleteFolder" v-show="rightClickFolderOrFile=='folder'"><i class="el-icon-close"></i><span>删除</span></v-contextmenu-item>
                <!--     文件右键菜单   -->
                <v-contextmenu-item @click="viewDetailFile" v-show="rightClickFolderOrFile=='file'"><i class="el-icon-warning-outline"></i><span>查看信息</span></v-contextmenu-item>
                <v-contextmenu-item @click="renameFile" v-show="rightClickFolderOrFile=='file'"><i class="el-icon-edit-outline"></i><span>重命名</span></v-contextmenu-item>
                <v-contextmenu-item @click="authFile" v-show="rightClickFolderOrFile=='file'"><i class="el-icon-link"></i><span>授权</span></v-contextmenu-item>
                <v-contextmenu-item @click="moveFile" v-show="rightClickFolderOrFile=='file'"><i class="el-icon-thumb"></i><span>移动</span></v-contextmenu-item>
                <v-contextmenu-item @click="preview" v-show="rightClickFolderOrFile=='file'"><i class="el-icon-brush"></i><span>预览</span></v-contextmenu-item>
                <v-contextmenu-item @click="borrow" v-show="rightClickFolderOrFile=='file'"><i class="el-icon-wallet"></i><span>借阅</span></v-contextmenu-item>
                <v-contextmenu-item @click="deleteFile" v-show="rightClickFolderOrFile=='file'"><i class="el-icon-close"></i><span>删除</span></v-contextmenu-item>
            </v-contextmenu>

            <!--      文件夹详情      -->
            <el-dialog :title="'文件夹详情'" :visible.sync="openFolderDetail" width="500px" append-to-body>
                <div class="detail">
                    <el-row>
                        <span>文件夹名称：</span><span>{{folderDetail.name}}</span>
                    </el-row>
                    <el-row>
                        <span>备注：</span><span>{{folderDetail.remark}}</span>
                    </el-row>
                    <el-row>
                        <span>路径：</span><span>{{folderDetail.npath}}</span>
                    </el-row>
                    <el-row>
                        <span>创建时间：</span><span>{{folderDetail.createTime}}</span>
                    </el-row>
                    <el-row>
                        <span>文件数量：</span><span>{{folderDetail.fileCount}}</span>
                    </el-row>
                </div>
            </el-dialog>
            <!--      文件详情      -->
            <el-dialog :title="'文件详情'" :visible.sync="openFileDetail" width="1000px" append-to-body>
                <div class="detail">
                    <div class="borrowTag">
                        <dict-tag :options="dict.type.archive_borrow_status" :value="fileDetail.brStatus"/>
                    </div>
                    <el-row>
                        <span>文件名称：</span><span>{{fileDetail.title}}</span>
                    </el-row>
                    <el-row>
                        <span>副标题：</span><span>{{fileDetail.subTitle}}</span>
                    </el-row>
                    <el-row>
                        <span>文件夹路径：</span><span>{{fileDetail.folderPath}}</span>
                    </el-row>
                    <el-row>
                        <span>副标题：</span><span>{{fileDetail.cabinetPath}}</span>
                    </el-row>
                    <el-row>
                        <span>备注：</span><span>{{fileDetail.remark}}</span>
                    </el-row>
                    <el-row>
                        <span>创建时间：</span><span>{{fileDetail.createTime}}</span>
                    </el-row>
                    <el-row>
                        <span>借阅记录：</span>
                    </el-row>
                </div>
            </el-dialog>
            <!--      文件夹，文件重命名      -->
            <el-dialog :title="renameTitle" :visible.sync="openRenameDialog" width="500px" append-to-body>
                <el-form label-width="80px">
                    <el-form-item label="新名称" prop="newName">
                        <el-input v-model="newName" placeholder="请输入新名称"/>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button type="primary" @click="submitRename">确 定</el-button>
                    <el-button @click="cancelRename">取 消</el-button>
                </div>
            </el-dialog>
            <!--   新建文件夹         -->
            <el-dialog title="新建文件夹" :visible.sync="openAddFolderDialog" width="500px" append-to-body>
                <el-form label-width="80px">
                    <el-form-item label="名称" prop="newAddFolderName">
                        <el-input v-model="newAddFolderName" placeholder="请输入文件夹名称"/>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button type="primary" @click="submitAddFolder">确 定</el-button>
                    <el-button @click="cancelAddFolder">取 消</el-button>
                </div>
            </el-dialog>
            <!--   移动         -->
            <el-dialog title="移动" :visible.sync="openMoveDialog" width="500px" append-to-body>
                <el-form label-width="80px">
                    <el-form-item label="文件夹" prop="newAddFolderName">
                        <treeselect v-model="moveFolderId" :options="folderTree" :show-count="true" placeholder="请选择文件夹" />
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button type="primary" @click="submitMove">确 定</el-button>
                    <el-button @click="cancelMove">取 消</el-button>
                </div>
            </el-dialog>

            <!--   预览         -->
            <el-dialog :title="rightClickName" :visible.sync="openPreviewDialog" width="1000px" append-to-body>
                <iframe :src="previewUrl" class="previewIframe"/>
            </el-dialog>

        </el-container>
</template>
<script>
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {treeselectCabinet} from "@/api/am/amCabinet"
import {treeselectFolder} from "@/api/am/amFolder"
import {queryFileByFolderId} from "@/api/am/amArchive";
import {ifHaveAuth} from "@/api/am/amBrowse"
import {viewFile,viewFolder,addFolder,renameFolder,renameFile,moveFolder,moveFile,deleteFolder,deleteFile,preview} from "@/api/am/amBrowse";

export default {
    name: "AmBrowse",
    components: {Treeselect},
    dicts: ['archive_borrow_status'],
    data() {
        return {
            //bigImg:大图标模式，col:列表模式
            mode:"bigImg",
            //右键点击位置
            rightClickFolderOrFile:"",
            rightClickId:undefined,
            rightClickName:"",
            //面包屑集合
            breadList:[],
            //查看详情
            openFolderDetail:false,
            openFileDetail:false,
            folderDetail:{},
            fileDetail:{},
            //重命名
            openRenameDialog:false,
            renameTitle:"",
            newName:"",
            //新建文件夹
            openAddFolderDialog:false,
            newAddFolderName:"新建文件夹",
            //移动
            openMoveDialog:false,
            moveFolderId:undefined,
            //预览
            previewType:["pdf","xls","xlsx","doc","docx","jpg","jpeg","png","txt","rtf","csv","ppt","pptx","bmp","gif"],
            openPreviewDialog:false,
            previewUrl:"",
            //左侧文件夹搜索
            folderName:"",
            folderTree: [],
            cabinetTree: [],
            defaultProps: {
                children: "children",
                label: "label"
            },
            queryParams:{},
            folderList:[],
            fileList:[],
            rootNodeId:1,
        };
    },
    watch: {
        // 根据名称筛选部门树
        folderName(val) {
            this.$refs.tree.filter(val);
        }
    },
    created() {
        //获取文件夹，和档案柜，下拉数据集
        this.getTreeselect();
        //查询根节点下的文件（初始化页面展示）
        this.handleQueryFile(this.rootNodeId);
    },
    mounted() {
        // this.$refs.tree.setCurrentKey(this.rootNodeId);
    },
    methods: {
        getTreeselect() {
            // treeselectCabinet().then(response => {
            //     this.cabinetTree = response.data;
            // });
            treeselectFolder().then(res=>{
                this.folderTree = res.data;
            })
        },
        // 筛选节点
        filterNode(value, data) {
            if (!value) return true;
            return data.label.indexOf(value) !== -1;
        },
        // 节点单击事件
        nodeClick(data) {
            console.log(data)
            this.handleQueryFile(data.id);
        },
        // 查询所有文件
        handleQueryFile(id){
            this.queryParams.folderId = id;
            queryFileByFolderId(id).then(res=>{
                if(res.code==200&&res.data){
                    //所选文件夹下的所有文件夹
                    this.folderList = res.data.folderList;
                    //所选文件夹下的所有文件
                    this.fileList = res.data.fileList;
                    console.log(this.folderList)
                    //组装面包屑
                    let breadArr = [];
                    let self = res.data.self;
                    if(self!=null){
                        let idPath = self.cpath;
                        let namePath = self.npath;
                        if(idPath&&idPath.length>0&&namePath&&namePath.length>0){
                            let cArr = idPath.split("/");
                            let nArr = namePath.split("/");
                            if(cArr.length==nArr.length){
                                cArr.forEach((item,index)=>{
                                    //斜杠开头，下标为0的时候，为空
                                    if(index!=0){
                                        let bread = {};
                                        bread.id = item;
                                        bread.name = nArr[index];
                                        breadArr.push(bread);
                                    }
                                })
                            }
                        }
                    }
                    //拼上自己
                    let bread = {};
                    bread.id = self.id;
                    bread.name = self.name;
                    breadArr.push(bread);
                    this.breadList = breadArr;
                }
            })
        },
        // 双击文件夹
        goInToFolder(id){
            //查询文件夹下所有文件
            this.handleQueryFile(id);
            //左侧树选中
            this.$refs.tree.setCurrentKey(id);
        },
        //格式化文件类型图片
        formatImg(name){
            let ext = this.getFileExt(name);
            console.log("文件扩展名为："+ext);
            if(ext){
                let lowExt = ext.toLowerCase();
                if(lowExt=="doc"||lowExt=="docx"){
                    return require('@/assets/images/am/filext/DOC.png');
                }else if(lowExt=="pdf"){
                    return require('@/assets/images/am/filext/PDF.png');
                }else if(lowExt=="ppt"){
                    return require('@/assets/images/am/filext/PPT.png');
                }else if(lowExt=="psd"){
                    return require('@/assets/images/am/filext/PSD.png');
                }else if(lowExt=="txt"){
                    return require('@/assets/images/am/filext/TXT.png');
                }else if(lowExt=="vsd"){
                    return require('@/assets/images/am/filext/VSD.png');
                }else if(lowExt=="xmap"){
                    return require('@/assets/images/am/filext/XMAP.png');
                }else if(lowExt=="ys"){
                    return require('@/assets/images/am/filext/YS.png');
                }else if(lowExt=="ai"){
                    return require('@/assets/images/am/filext/AI.png');
                }else if(lowExt=="mp3"||lowExt=="mp4"||lowExt=="wmv"||lowExt=="rmvb"||lowExt=="mkv"||lowExt=="avi"){
                    return require('@/assets/images/am/filext/VIDEO.png');
                }else if(lowExt=="xls"||lowExt=="xlsx"){
                    return require('@/assets/images/am/filext/ELX.png');
                }else if(lowExt=="rar"||lowExt=="zip"){
                    return require('@/assets/images/am/filext/RAR.png');
                }else{
                    return require('@/assets/images/am/filext/FILE.png');
                }
            }
        },
        // 获取文件名称
        getFileName(name) {
            if (name.lastIndexOf("/") > -1) {
                return name.slice(name.lastIndexOf("/") + 1);
            } else {
                return "";
            }
        },
        // 获取扩展名
        getFileExt(name){
            // let n = this.getFileName(name);
            let ar = name.split(".");
            return ar[ar.length-1];
        },
        // 阻止右键菜单行为事件冒泡
        rightClick(type,id,name){
            console.log(type)
            this.rightClickFolderOrFile = type;
            this.rightClickId = id;
            this.rightClickName = name;
        },
        // 更改展示模式
        changeMode(mode){
            this.mode=mode;
        },
        // 刷新
        refreshFolder(){
            this.handleQueryFile(this.queryParams.folderId);
            this.$modal.msgSuccess("刷新成功");
        },
        // 检查我有没有权限
        async meIfHaveAuth(data){
            let res = await ifHaveAuth(data);
            return res;
        },
        // 查看详情 -- 文件夹
        viewDetailFolder() {
            // let data = {
            //     "id":this.rightClickId,
            //     "type":"folder",
            //     "operate":"view"
            // }
            // async await 通过修饰的方法会返回Promise对象，直接使用then方法获取回调函数中的值
            // this.meIfHaveAuth(data).then(res=>{
            //     console.log(res)
            // })

            viewFolder(this.rightClickId).then(r=>{
                this.folderDetail = r.data
                this.openFolderDetail = true;
            })

        },
        // 查看详情 -- 文件
        viewDetailFile(){
            viewFile(this.rightClickId).then(r=>{
                this.fileDetail = r.data
                this.openFileDetail = true;
            })
        },
        //重命名 -- 文件夹
        renameFolder(){
            this.newName = this.rightClickName;
            this.openRenameDialog = true;
            this.renameTitle = "文件夹重命名";
        },
        //重命名 -- 文件
        renameFile(){
            this.newName = this.rightClickName;
            this.openRenameDialog = true;
            this.renameTitle = "档案重命名";
        },
        submitRename(){
            let data={"id":this.rightClickId,"name":this.newName}
            if(this.rightClickFolderOrFile == "folder"){
                renameFolder(data).then(res=>{
                    if(200==res.code){
                        this.$modal.msgSuccess("重命名成功");
                        this.openRenameDialog = false;
                        this.submitCallBackRefresh();
                    }
                })
            }
            if(this.rightClickFolderOrFile == "file"){
                renameFile(data).then(res=>{
                    if(200==res.code){
                        this.$modal.msgSuccess("重命名成功");
                        this.openRenameDialog = false;
                        this.submitCallBackRefresh();
                    }
                })
            }
        },
        cancelRename(){
            this.openRenameDialog = false;
        },
        //授权 -- 文件夹
        authFolder(){
            this.$modal.msgSuccess("待开发");
        },
        //授权 -- 文件
        authFile(){
            this.$modal.msgSuccess("待开发");
        },
        //移动 -- 移动文件夹
        moveFolder(){
            this.openMoveDialog = true;
        },
        //移动 -- 移动文件
        moveFile(){
            this.openMoveDialog = true;
        },
        submitMove(){
            if(!this.moveFolderId||this.moveFolderId.length<=0){
                this.$modal.msgError("请选择目标文件夹");
                return;
            }
            let data={"id":this.rightClickId,"targetFolderId":this.moveFolderId}
            if(this.rightClickFolderOrFile == "folder"){
                moveFolder(data).then(res=>{
                    if(200==res.code){
                        this.submitCallBackRefresh();
                        this.$modal.msgSuccess("重命名成功");
                        this.openMoveDialog = false;
                    }
                })
            }
            if(this.rightClickFolderOrFile == "file"){
                moveFile(data).then(res=>{
                    if(200==res.code){
                        this.submitCallBackRefresh();
                        this.$modal.msgSuccess("重命名成功");
                        this.openMoveDialog = false;
                    }
                })
            }
        },
        cancelMove(){
            this.openMoveDialog = false;
        },
        //预览
        preview(){
            preview(this.rightClickId).then(res=>{
                if(200==res.code){
                    // 判断格式是否支持
                    let url = process.env.VUE_APP_BASE_API + res.data;
                    let ext = this.getFileExt(url);
                    if(this.previewType.findIndex(item=>item===ext)!=-1){
                        this.openPreviewDialog = true;
                        this.previewUrl = url;
                    }else{
                        this.$modal.msgSuccess("该档案文件类型不支持在线预览");
                    }
                }
            })
        },
        //借阅
        borrow(){
            this.$modal.msgSuccess("待开发");
        },
        // 删除 -- 文件夹
        deleteFolder(){
            this.$modal.confirm('是否确认删除该文件夹').then( ()=> {
                return deleteFolder(this.rightClickId);
            }).then(() => {
                this.$modal.msgSuccess("删除成功");
                this.submitCallBackRefresh();
            }).catch(() => {
            });
        },
        // 删除 -- 文件
        deleteFile(){
            this.$modal.confirm('是否确认删除该档案').then( ()=> {
                return deleteFile(this.rightClickId);
            }).then(() => {
                this.$modal.msgSuccess("删除成功");
                this.submitCallBackRefresh();
            }).catch(() => {
            });
        },
        // 新建文件夹
        openAddFolder(){
            this.openAddFolderDialog = true;
        },
        submitAddFolder(){
            if(!this.newAddFolderName||this.newAddFolderName.length<=0){
                this.$modal.msgError("请输入文件夹名称");
                return;
            }
            let data={"parentId":this.queryParams.folderId,"name":this.newAddFolderName}
            addFolder(data).then(res=>{
                if(200==res.code){
                    this.$modal.msgSuccess("重命名成功");
                    this.submitCallBackRefresh();
                }
            })
        },
        cancelAddFolder(){
            this.openAddFolderDialog = false;
        },
        // 档案上传
        addFile(){
            this.$router.push({path: "/am/amArchive/form/add", query: {folderId:this.queryParams.folderId}})
        },
        // 提交完成后，静默刷新
        submitCallBackRefresh(){
            this.getTreeselect();
            this.handleQueryFile(this.queryParams.folderId);
        }
    }
};
</script>

<style scoped lang="scss">
.container{
    height: calc(100vh - 91px);
    .folder-aside{
        width: 300px;
        height: calc(100vh - 91px);
        border-right: 1px solid #dddddd;
        margin: 0px;
        -webkit-box-shadow: 1px 0 6px rgb(0 21 41 / 35%);
        box-shadow: 1px 0 6px rgb(0 21 41 / 35%);
    }
    .file-container{
        padding: 0px 10px;
        width: 100%;
        .bread{
            position: fixed;
            background-color: #ffffff;
            padding: 20px 10px 10px 20px;
            width: 100%;
            z-index: 2;
        }
        .file-list{
            height: calc(100vh - 91px);
            display: flex;
            flex-wrap: wrap;
            padding-top: 50px;
            padding-left: 10px;
            overflow: scroll;
        }
        //大图模式
        .bigImg{
            flex-direction: row;
            .item{
                display: flex;
                flex-direction: column;
                padding: 5px;
                height: 150px;
                width: 130px;
                .img{
                    width: 120px;
                    height: 120px;
                }
                .file-name{
                    text-align: center;
                    font-size: 14px;
                    color: #606266;
                    height: 20px;
                    overflow: hidden;
                    width: 120px;
                    white-space: nowrap;
                    text-overflow: ellipsis;
                }
            }
        }
        //列表模式
        .col{
            flex-direction: column;
            .item{
                display: flex;
                flex-direction: row;
                padding: 10px;
                height: 55px;
                width: 270px;
                .img{
                    width: 35px;
                    height: 35px;
                }
                .file-name{
                    text-align: left;
                    line-height: 35px;
                    font-size: 14px;
                    color: #606266;
                    height: 35px;
                    overflow: hidden;
                    width: 215px;
                    white-space: nowrap;
                    text-overflow: ellipsis;
                    padding-left: 10px;
                    cursor: default;
                }
            }
        }
        // 鼠标上浮更改背景色
        .item:hover{
            background-color: #eeeeee;
        }
    }
}

.detail{
    .el-row{
        padding: 5px 10px;
    }
    .borrowTag{

    }
}

.previewIframe{
    width: 100%;
    height: 800px;
    border: none;
}

.v-contextmenu{
    width: 150px;
    .v-contextmenu-item{
        padding: 10px 0px;
        text-align: center;
        width: 150px;
        color: #606266;
        span{
            padding-left: 5px;
        }
    }
}
</style>
